package com.homegoods.home.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.homegoods.home.R;
import com.homegoods.home.databinding.HomeActivitySearchBinding;
import com.homegoods.home.model.SearchListModel;
import com.homegoods.home.utils.SearchHistoryUtil;
import com.homegoods.resource.Constant;
import com.homegoods.aroutercomment.ARouterPath;
import com.kedll.library.KBaseActivity;
import com.kedll.library.adapter.MultiTypeAdapter;
import com.kedll.library.util.KeyBoardUtils;
import com.kedll.library.util.MyUtils;
import com.kedll.library.util.ToastUtil;

import java.util.List;


/**
 * 搜索页面
 * <p>
 * 搜索历史
 * <p>
 * 大家都在搜
 *
 * @author QiQi
 */
@Route(path = ARouterPath.PATH_SEARCH)
public class SearchActivity extends KBaseActivity<HomeActivitySearchBinding> implements View.OnClickListener {

    MultiTypeAdapter hotAdapter;

    MultiTypeAdapter historyAdapter;


    @Override
    protected int getLayout() {
        return R.layout.home_activity_search;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        historyAdapter = new FlexBoxAdapter(getApplicationContext(), 4);
        hotAdapter = new FlexBoxAdapter(getApplicationContext(), 4);
        //搜索历史
        initListView(mBinding.gvHistory, historyAdapter);

        //热门搜索
        initListView(mBinding.gvHot, hotAdapter);
        // 获取热门
        getHotSearchKeyWordList();
    }

    private void initListView(RecyclerView list, MultiTypeAdapter adapter) {
        list.setLayoutManager(MyUtils.getFlexBoxLayoutManager(this));
        list.setHasFixedSize(false);
        list.setNestedScrollingEnabled(false);
        list.setAdapter(adapter);
    }

    /**
     * 热门搜索关键词
     */
    void getHotSearchKeyWordList() {
        //todo 通过接口请求热门搜索关键词
    }

    @Override
    protected void initEvent() {

        mBinding.etSearch.setOnSearchClickListener((view, keyword) -> {
            String content = mBinding.etSearch.getText().toString();
            if (!TextUtils.isEmpty(content)) {
                search(content);
            } else {
                ToastUtil.showSnackbar(view, "请输入搜索内容");
            }
            mBinding.etSearch.setText("");
        });
        mBinding.tvCancel.setOnClickListener(v -> {
            KeyBoardUtils.hideKeyBoard(SearchActivity.this);
            finish();
        });
        //删除监听
        mBinding.ivClear.setOnClickListener(v -> {
            historyAdapter.clear();
            historyAdapter.notifyDataSetChanged();
            SearchHistoryUtil.clearSearchList();
        });

    }

    /**
     * 保存为历史并搜索
     *
     * @param content
     */
    private void search(String content) {
        ARouter.getInstance()
                .build(ARouterPath.PATH_SEARCH_RESULT)
                .withString("searchContent", content)
                .navigation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getSearchList(); // 获取本地保存的历史记录
    }

    /**
     * 获取历史记录
     */
    void getSearchList() {
        historyAdapter.clear();
        List<SearchListModel> searchList = SearchHistoryUtil.getSearchList();
        if (searchList != null && searchList.size() > 0) {
            for (SearchListModel searchListModel : searchList) {
                historyAdapter.addItem(searchListModel.createItem(historyAdapter));
            }
        }
        historyAdapter.notifyDataSetChanged();
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.gv_history) {
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK && data == null) {
            return;
        }

        if (requestCode == 100) {
            String result = data.getStringExtra(Constant.SCAN_RESULT_KEY);
            mBinding.etSearch.setText(result);
            search(result);
        }
    }

    private static class FlexBoxAdapter extends MultiTypeAdapter {

        private int itemWidth;

        public FlexBoxAdapter(Context context, int itemCount) {
            itemWidth = context.getResources().getDisplayMetrics().widthPixels / itemCount;
        }

        @Override
        public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
            super.onBindViewHolder(holder, position);
            View view = holder.getBinding().getRoot().findViewById(R.id.tv_history);
            ViewGroup.LayoutParams lp = view.getLayoutParams();
            if (lp instanceof FlexboxLayoutManager.LayoutParams) {
                FlexboxLayoutManager.LayoutParams flexboxLp = (FlexboxLayoutManager.LayoutParams) lp;
                flexboxLp.setMinWidth(itemWidth);
                flexboxLp.setFlexGrow(1.0f);
            }

        }
    }
}
